package com.hnust.controller.subject;

import com.hnust.domain.*;
import com.hnust.fx.DialogBuilder;
import com.hnust.fx.FXMLController;
import com.hnust.service.SubjectServices;
import com.hnust.store.DataStore;
import com.hnust.store.SubjectStore;
import com.hnust.view.subject.dialog.WindowPaperView;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXCheckBox;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.util.StringConverter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

@FXMLController
public class BatchImportController implements Initializable {
    public Label courseDataLabel;
    public JFXButton downloadBtn;
    public JFXButton uploadBtn;
    public TableColumn<BulkImport, Boolean> tc_chk;
    public JFXCheckBox cb;
    public TableColumn<BulkImport, String> tc_answer;
    public TableColumn<BulkImport, String> tc_operation;
    public VBox loadingUploadInfo;
    public HBox btnGroupInfo;
    public VBox batchImportWindow;
    public HBox secondHbox;
    public HBox firstHbox;
    //接收表格的数据
    public ObservableList<BulkImport> observableList = FXCollections.observableArrayList();
    public JFXButton allImportBtn;

    @Autowired
    private SubjectServices subjectServices;
    //查看答案
    @Autowired
    private DataStore dataStore;
    //修改题目
    @Autowired
    private WindowPaperView windowPaperView;
    @FXML
    ComboBox<CourseData> comb;
    private String selectCourseId;
    //顶部提醒框
    @FXML
    public VBox remind;
    @FXML
    public VBox form;
    @FXML
    public TableView<BulkImport> tableSize;

    @Autowired
    private SubjectStore subjectStore;

    private static final Logger logger = LogManager.getLogger(BatchImportController.class);

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableSize.prefWidthProperty().bind(form.widthProperty().multiply(0.94));
        remind.prefWidthProperty().bind(firstHbox.widthProperty().multiply(0.94));

        comb.setConverter(new StringConverter<CourseData>() {
            @Override
            public String toString(CourseData object) {
                return object.getName();
            }

            @Override
            public CourseData fromString(String string) {
                return null;
            }
        });
        comb.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                selectCourseId = newValue.getId();
            }
        });
        //listenChange();
        batchImportWindow.parentProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                subjectStore.setFirst(true);//设置题目列表界面重新加载
                getCombData();
            } else {
                clear();
                selectCourseId = null;
            }
        });
        initTableView();
    }

    public class CheckBoxCell extends TableCell<BulkImport, Boolean> {
        @Override
        protected void updateItem(Boolean item, boolean empty) {
            super.updateItem(item, empty);
            final TableCell<BulkImport, Boolean> cell = this;
            if (!empty) {
                HBox hBox = new HBox();
                hBox.setAlignment(Pos.CENTER);
                JFXCheckBox checkBox = new JFXCheckBox();
                checkBox.setSelected(item);
                //给CheckBox添加变化事件
                checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
                    BulkImport data = (BulkImport) cell.getTableRow().getItem();
                    logger.info(data);
                    //选中
                    if (newValue) {
                        data.setChecked(true);
                        //表格的任意一行的check都不是false,则返回false
                        boolean bl = tableSize.getItems().stream().anyMatch(bulkImport -> !bulkImport.getChecked());
                        if (!bl) {
                            cb.setSelected(true);
                        }
                    } else {
                        //没选中
                        data.setChecked(false);
                        cb.setSelected(false);
                    }
                    tableSize.refresh();
                });
                hBox.getChildren().add(checkBox);
                this.setGraphic(hBox);
            }
        }
    }

    public class OperationCell extends  TableCell<BulkImport,String>{
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            final TableCell<BulkImport,String> cell = this;
            if (!empty) {
                HBox hBox = new HBox();
                hBox.setAlignment(Pos.CENTER);
                hBox.setSpacing(10);
                JFXButton btn1=new JFXButton("详情");
                btn1.getStyleClass().add("modify-color");
                btn1.setDisableVisualFocus(false);
                btn1.setMinWidth(40);
                //增加详情弹窗
                btn1.setOnAction(event -> {
                    BulkImport bulkImport = (BulkImport) cell.getTableRow().getItem();
                    dataStore.setBulkImport(bulkImport);
                    new DialogBuilder(uploadBtn).setTitle("查看题目详情").setBody(windowPaperView.getView()).
                            setPositiveBtn("确定", "#3333cc").setSize(800.0,500.0).create();
                });
                JFXButton btn2=new JFXButton("删除");
                btn2.getStyleClass().add("warn-color");
                btn2.setDisableVisualFocus(false);
                btn2.setMinWidth(40);
                btn2.setOnAction(event -> {
                    observableList.remove(getIndex());
                    tableSize.refresh();
                });
                hBox.getChildren().addAll(btn1,btn2);
                this.setGraphic(hBox);
            }
        }
    }

    public void initTableView() {
        cb.selectedProperty().addListener((observable, oldValue, newValue) -> {
            //如果是选中
            if (newValue) {
                tableSize.getItems().forEach(bulkImport -> bulkImport.setChecked(true));
            } else {
                //非选中
                tableSize.getItems().forEach(bulkImport -> bulkImport.setChecked(false));
            }
            tableSize.refresh();
        });
        tc_chk.setCellFactory(param -> new CheckBoxCell());
        tc_operation.setCellFactory(param -> new OperationCell());
    }

    //选择WORD文档上传
    public void chooseFile() {
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Text Files", "*.doc", " *.docx");
        fileChooser.getExtensionFilters().add(filter);
        File file = fileChooser.showOpenDialog(null);
        if(file!=null){
            subjectServices.uploadFile(file,uploadBtn,selectCourseId,tableSize,form,
                    loadingUploadInfo,btnGroupInfo,observableList,cb);
        }
    }

    //下载批量导入模板
    public void downloadFile() {
        subjectServices.downloadFile(downloadBtn);
    }

    //取消，删除所有
    public void cancel() {
        clear();
    }

    //批量导入
    public void allImport() {
        List<SubjectDataInfo> subjectDataInfoList = new ArrayList<>();
        tableSize.getItems().forEach(bulkImport -> {
            List<AnswerObjRecoed> answerObjRecoedList = new ArrayList<>();
            if (bulkImport.getChecked()) {
                SubjectDataInfo subjectDataInfo = new SubjectDataInfo();
                subjectDataInfo.setId(bulkImport.getQueId());
                subjectDataInfo.setCourse_id(bulkImport.getCouId());
                subjectDataInfo.setContent(bulkImport.getContent());
                subjectDataInfo.setChapter_id(bulkImport.getChaId());
                subjectDataInfo.setCourseTargetId(bulkImport.getCouTarId());
                subjectDataInfo.setKnowledgePointer(bulkImport.getPoint());
                subjectDataInfo.setDifficult(bulkImport.getLevel());
                subjectDataInfo.setResolve(bulkImport.getAnalysis());
                subjectDataInfo.setType_id(bulkImport.getQueTypId());
                bulkImport.getAnswerList().forEach(alternativeAnswerRecord -> {
                    if (!alternativeAnswerRecord.getContent().isEmpty()) {
                        AnswerObjRecoed answerObjRecoed = new AnswerObjRecoed();
                        answerObjRecoed.setContent(alternativeAnswerRecord.getContent());
                        answerObjRecoed.setRight(alternativeAnswerRecord.getRight() == 1);
                        answerObjRecoed.setAltAnsId(alternativeAnswerRecord.getAltAnsId());
                        answerObjRecoedList.add(answerObjRecoed);
                    }
                });
                subjectDataInfo.setAnswer(answerObjRecoedList);
                subjectDataInfoList.add(subjectDataInfo);
            }
        });
        if (subjectDataInfoList.size() != 0) {
            SubjectDataListReq subjectDataListReq = new SubjectDataListReq();
            subjectDataListReq.setSubjectDataList(subjectDataInfoList);
            subjectDataListReq.setToken(dataStore.getToken());
            subjectDataListReq.setId(dataStore.getTeacher_id());
            subjectServices.addSub(allImportBtn,subjectDataListReq);
        } else {
            new DialogBuilder(uploadBtn).setTitle("提示").setMessage("无法进行操作，选中的内容为空！").
                    setPositiveBtn("确定", "#ff3333").create();
        }

    }

    //获取下拉框数据
    public void getCombData() {
        subjectServices.getCourseData(courseDataLabel, comb,0,null);
    }

    //清空此页面所有数据
    public void clear() {
        observableList.clear();
        tableSize.getItems().clear();
        tableSize.refresh();
        form.setVisible(false);
        form.setManaged(false);
        cb.setSelected(false);
    }

}